import { BaseReactElementState, BaseReactElement, reactControl, BaseReactElementControl } from "pao-aop-client";
import React from "react";
import { addon } from "pao-aop";
import { WingBlank, List, WhiteSpace, InputItem, TextareaItem, Button, Toast, Picker, Calendar } from "antd-mobile";
import { AppServiceUtility } from "src/projects/app/appService";
import { ROUTE_PATH, getAppPermissonObject } from "src/projects/app/util-tool";
import { request, setMainFormTitle } from "src/business/util_tool";
import zhCN from 'antd-mobile/lib/calendar/locale/zh_CN';
import { FileUploadBtn } from "src/business/components/buss-components/file-operation-btn/file-upload-btn";
import { remote } from "src/projects/remote";
import { beforeUpload } from "src/projects/app/util-tool";
import { Form } from "antd";
import { IntelligentElderlyCareAppStorage } from "src/projects/app/appStorage";
import { NTBraftEditor } from "src/business/components/buss-components/rich-text-editor";
import { LOCAL_FUNCTION_LIST } from "src/business/mainForm/backstageManageMainForm";
// import moment from "moment";
/**
 * 组件：发布活动状态
 */
export interface ChangeActivityViewState extends BaseReactElementState {
    // 活动名称
    activity_name?: any;
    // 活动类型
    activity_type_id?: any;
    activity_type_list?: any;
    activity_type_show_value?: any;
    // 活动室
    activity_room_id?: any;
    activity_room_list?: any;
    activity_room_show_value?: any;
    // 活动图片
    photo?: any;
    // 商家
    organization_id?: any;
    organization_list?: any;
    organization_show_value?: any;
    // 最大参与人数
    max_quantity?: any;
    // 活动开始时间
    begin_date?: any;
    // 活动结束时间
    end_date?: any;
    // 活动地点
    address?: any;
    // 活动场室
    activity_room?: any;
    // 联系人
    contacts?: any;
    // 联系人电话
    phone?: any;
    // 金额
    amount?: any;
    // 活动介绍
    introduce?: any;
    // 是否已发送
    isSend?: boolean;

    show?: any;
    config?: any;

    // 活动详情
    activity_info?: any;
    // 是否原作者
    isAuthor?: boolean;
}

const now = new Date();

/**
 * 组件：发布活动
 * 发布活动
 */
export class ChangeActivityView extends BaseReactElement<ChangeActivityViewControl, ChangeActivityViewState> {
    originbodyScrollY = document.getElementsByTagName('body')[0].style.overflowY;
    constructor(props: any) {
        super(props);
        this.state = {
            activity_name: '',
            activity_type_id: '',
            activity_type_list: [],
            activity_type_show_value: '',
            activity_room_id: '',
            activity_room_list: [],
            activity_room_show_value: '',
            photo: [],
            organization_id: '',
            organization_list: [],
            organization_show_value: '',
            max_quantity: 0,
            begin_date: '',
            end_date: '',
            address: '',
            activity_room: '',
            contacts: '',
            phone: '',
            amount: 0,
            introduce: '',
            isSend: false,
            show: false,
            config: '',
            activity_info: [],
            isAuthor: false,
        };
    }
    componentDidMount() {
        const AppPermission = JSON.parse(localStorage.getItem(LOCAL_FUNCTION_LIST)!);
        let user = IntelligentElderlyCareAppStorage.getCurrentUser();
        if (!user) {
            this.props.history!.push(ROUTE_PATH.login);
            return;
        }
        // 活动类型数据
        request(this, AppServiceUtility.activity_service.get_activity_type_list!({}, 1, 99))
            .then((datas: any) => {
                this.setState({
                    activity_type_list: datas.result || [],
                });
            });
        // 活动室
        request(this, AppServiceUtility.activity_service.get_activity_room_list!({ org_id: true }, 1, 99))
            .then((datas: any) => {
                this.setState({
                    activity_room_list: datas.result || [],
                });
            });
        // // 商家数据
        // request(this, AppServiceUtility.person_org_manage_service.get_organization_list!({}, 1, 9999))
        //     .then((datas: any) => {
        //         this.setState(
        //             {
        //                 organization_list: datas.result || [],
        //             }
        //         );
        //     });
        if (this.props.match!.params.key) {
            request(this, AppServiceUtility.activity_service.get_activity_list!({ 'id': this.props.match!.params.key, all: true }))
                .then((data: any) => {
                    // 有这篇文章或者作者或者权限者
                    if ((data.result.length > 0 && data.result[0]['apply_user_id'] && data.result[0]['apply_user_id'] === user.id) || (AppPermission && getAppPermissonObject(AppPermission, '活动列表', '编辑'))) {
                        this.setState({
                            activity_info: data.result[0],
                            activity_name: data.result[0]['activity_name'],
                            max_quantity: data.result[0]['max_quantity'],
                            begin_date: data.result[0]['begin_date'],
                            end_date: data.result[0]['end_date'],
                            address: data.result[0]['address'],
                            // activity_room: data.result[0]['activity_room'],
                            contacts: data.result[0]['contacts'],
                            phone: data.result[0]['phone'],
                            amount: data.result[0]['amount'],
                            photo: data.result[0]['photo'],
                            introduce: data.result[0]['introduce'],
                            organization_id: data.result[0]['organization_id'],
                            organization_show_value: [data.result[0]['organization_id']],
                            activity_type_id: data.result[0]['activity_type_id'],
                            activity_type_show_value: [data.result[0]['activity_type_id']],
                            activity_room_id: data.result[0]['activity_room_id'],
                            activity_room_show_value: [data.result[0]['activity_room_id']],
                            isAuthor: true,
                        });
                    } else {
                        this.setState({
                            activity_info: [],
                            isAuthor: false,
                        });
                    }
                });
        }
    }
    changeValue = (e: any, inputName: any) => {
        this.setState({
            [inputName]: e
        });
    }
    changeSelect = (e: any, selectNameId: any, selectName: any) => {
        this.setState({
            [selectNameId]: e[0],
            [selectName]: e,
        });
    }
    ActivityPush = (): boolean => {
        const { activity_name, activity_type_id, max_quantity, begin_date, end_date, address, activity_room_id, contacts, phone, photo, introduce, amount, isAuthor, activity_info } = this.state;
        if (activity_name === '') {
            Toast.fail('请填写活动名称！', 1);
            return false;
        }
        if (activity_type_id === '') {
            Toast.fail('请选择活动类型！', 1);
            return false;
        }
        // if (organization_id === '') {
        //     Toast.fail('请选择商家！', 1);
        //     return false;
        // }
        if (max_quantity === '') {
            Toast.fail('请输入最大参与人数！', 1);
            return false;
        }
        if (isNaN(Number(max_quantity))) {
            Toast.fail('请输入正确的最大参与人数！', 1);
            return false;
        }
        if (begin_date === '' || begin_date === undefined) {
            Toast.fail('请选择活动开始时间！', 1);
            return false;
        }
        if (end_date === '' || end_date === undefined) {
            Toast.fail('请选择活动结束时间！', 1);
            return false;
        }
        if (address === '') {
            Toast.fail('请填写活动地点！', 1);
            return false;
        }
        // if (activity_room_id === '') {
        //     Toast.fail('请选择活动场室！', 1);
        //     return false;
        // }
        if (contacts === '') {
            Toast.fail('请填写联系人！', 1);
            return false;
        }
        if (phone === '') {
            Toast.fail('请填写联系人电话！', 1);
            return false;
        }
        if (!(/^1[3456789]\d{9}$/.test(phone))) {
            Toast.fail('请填写正确的联系人电话！', 1);
            return false;
        }
        if (amount === '') {
            Toast.fail('请填写活动金额！', 1);
            return false;
        }
        var param: any = {
            activity_name,
            activity_type_id,
            // organization_id,
            max_quantity: Number(max_quantity),
            begin_date: new Date(new Date(begin_date).getTime() + 28800000),
            end_date: new Date(new Date(end_date).getTime() + 28800000),
            address,
            contacts,
            phone,
            amount,
            photo: photo || '',
            introduce: introduce || '',
        };
        if (activity_room_id) {
            param['activity_room_id'] = activity_room_id;
        }
        if (isAuthor) {
            param['id'] = activity_info.id;
        }
        Toast.loading('提交中...', 11, () => {
        });
        let st = setTimeout(
            () => {
                Toast.hide();
                Toast.fail('提交失败，请稍候再试', 3);
            },
            10000
        );
        request(this, AppServiceUtility.activity_service.update_activity!(param))
            .then((datas: any) => {
                if (datas === 'Success') {
                    clearTimeout(st);
                    Toast.hide();
                    Toast.success('提交成功', 3);
                    setTimeout(
                        () => {
                            this.props.history!.push(ROUTE_PATH.myRelease + '/活动');
                        },
                        3000
                    );
                } else {
                    clearTimeout(st);
                    Toast.hide();
                    Toast.fail(`提交失败：${datas}`, 3);
                }
            })
            .catch(error => {
                clearTimeout(st);
                Toast.hide();
                Toast.fail(error.message);
            });
        return false;
    }
    onChange = (value: any) => {
        console.log('onChange', value);
    }
    onValueChange = (...args: any) => {
        console.log('onValueChange', args);
    }
    onPicChange = (files: any, type: any, index: any) => {
        console.log(files);
        this.setState({
            photo: files,
        });
    }
    renderBtn(zh: any, en: any, config: any = {}) {
        config.locale = zhCN;
        return (
            <List.Item
                arrow="horizontal"
                onClick={() => {
                    document.getElementsByTagName('body')[0].style.overflowY = 'hidden';
                    this.setState({
                        show: true,
                        config,
                    });
                }}
            >
                {zh}
            </List.Item>
        );
    }

    onConfirm = (begin_date: any, end_date: any) => {
        document.getElementsByTagName('body')[0].style.overflowY = this.originbodyScrollY;
        this.setState({
            show: false,
            begin_date,
            end_date,
        });
    }

    onCancel = () => {
        document.getElementsByTagName('body')[0].style.overflowY = this.originbodyScrollY;
        this.setState({
            show: false,
            begin_date: undefined,
            end_date: undefined,
        });
    }

    render() {
        if (this.props.match!.params.key) {
            setMainFormTitle('活动编辑');
        } else {
            setMainFormTitle('活动发布');
        }
        const { activity_type_list, activity_type_show_value, activity_room_list, activity_room_show_value, begin_date, end_date, activity_name, photo, max_quantity, address, contacts, phone, amount, introduce, isAuthor } = this.state;

        const { getFieldDecorator } = this.props.form!;

        // 构建活动类型数据源
        let activity_type_list_source: any[] = [];
        activity_type_list!.map((item: any) => {
            activity_type_list_source.push({
                label: item.name,
                value: item.id,
            });
        });
        // 构建活动类型数据源
        let activity_room_list_source: any[] = [];
        activity_room_list_source.push({
            label: '不选择',
            value: false,
        });
        if (activity_room_list.length > 0) {
            activity_room_list!.map((item: any) => {
                activity_room_list_source.push({
                    label: item.activity_room_name,
                    value: item.id,
                });
            });
        }
        // 构建商家数据源
        // let organization_list_source: any[] = [];
        // organization_list!.map((item: any) => {
        //     organization_list_source.push({
        //         label: item.name,
        //         value: item.id,
        //     });
        // });
        const
            borderBoth = {
                borderTop: '1px solid #ddd',
                borderBottom: '1px solid #ddd',
            };
        let roomstring = '活动场室';
        if ((activity_room_list_source.length === 0)) {
            roomstring += `（当前无可选活动室）`;
        }
        return (
            <div>
                <List renderHeader={() => '活动名称'}>
                    <InputItem value={activity_name ? activity_name : ''} clear={true} placeholder="请填写活动名称" onChange={(e) => this.changeValue(e, 'activity_name')} />
                </List>
                <List renderHeader={() => '活动类型'}>
                    <Picker data={activity_type_list_source} cols={1} value={activity_type_show_value} onChange={(e) => this.changeSelect(e, 'activity_type_id', 'activity_type_show_value')}>
                        <List.Item arrow="horizontal" style={borderBoth}>活动类型</List.Item>
                    </Picker>
                </List>
                <List renderHeader={() => '活动图片'}>
                    {getFieldDecorator('picture', {
                        initialValue: photo ? photo : '',
                        rules: [{
                            required: false,
                        }],
                    })(
                        <FileUploadBtn list_type={"picture-card"} contents={"plus"} action={remote.upload_url} beforeUpload={beforeUpload} onChange={(e) => this.changeValue(e, 'photo')} />
                    )}
                    <WhiteSpace size="xs" />
                </List>
                {/* <List renderHeader={() => '商家'}>
                    <Picker data={organization_list_source} cols={1} value={organization_show_value} onChange={(e) => this.changeSelect(e, 'organization_id', 'organization_show_value')}>
                        <List.Item arrow="horizontal" style={borderBoth}>商家</List.Item>
                    </Picker>
                </List> */}
                <List renderHeader={() => '最大参与人数'}>
                    <InputItem value={max_quantity ? max_quantity : ''} placeholder="请输入最大参与人数" onChange={(e) => this.changeValue(e, 'max_quantity')} />
                </List>
                <List
                    renderHeader={() => {
                        if (begin_date && end_date) {
                            return begin_date.toLocaleString() + '-' + end_date.toLocaleString();
                        }
                        return '选择活动时间';
                    }}
                >
                    {this.renderBtn('选择活动时间', '选择活动时间', {
                        pickTime: true,
                        onSelect: (date: any, state: any) => {
                            console.log('onSelect', date, state);
                            // return [date, new Date(+now - 604800000)];
                        },
                    })}
                </List>
                <List renderHeader={() => '活动地点'}>
                    <TextareaItem value={address ? address : ''} placeholder="请输入活动地点" rows={3} autoHeight={true} onChange={(e) => this.changeValue(e, 'address')} />
                </List>
                <List renderHeader={() => roomstring}>
                    <Picker data={activity_room_list_source} cols={1} value={activity_room_show_value} onChange={(e) => this.changeSelect(e, 'activity_room_id', 'activity_room_show_value')}>
                        <List.Item arrow="horizontal" style={borderBoth}>活动场室</List.Item>
                    </Picker>
                </List>
                <List renderHeader={() => '联系人'}>
                    <InputItem value={contacts ? contacts : ''} placeholder="请输入联系人" onChange={(e) => this.changeValue(e, 'contacts')} />
                </List>
                <List renderHeader={() => '联系人电话'}>
                    <InputItem value={phone ? phone : ''} placeholder="请输入联系人电话" onChange={(e) => this.changeValue(e, 'phone')} />
                </List>
                <List renderHeader={() => '活动金额'}>
                    <InputItem value={amount ? amount : ''} placeholder="请输入活动金额" onChange={(e) => this.changeValue(e, 'amount')} />
                </List>
                <List renderHeader={() => '活动介绍'}>
                    <NTBraftEditor value={introduce ? introduce : ''} onChange={(e) => this.changeValue(e, 'introduce')} remoteUrl={remote.upload_url} />
                </List>
                <WhiteSpace size="lg" />
                <WhiteSpace size="lg" />
                <WingBlank size="lg">
                    <Button type="primary" onClick={this.ActivityPush}>{isAuthor === true ? '保存修改' : '发布'}</Button>
                </WingBlank>
                <WhiteSpace size="lg" />
                <WhiteSpace size="lg" />
                <Calendar
                    {...this.state.config}
                    visible={this.state.show}
                    onCancel={this.onCancel}
                    onConfirm={this.onConfirm}
                    defaultValue={begin_date && end_date ? [new Date(begin_date), new Date(end_date)] : null}
                    defaultDate={now}
                    minDate={new Date(+now - 5184000000)}
                    maxDate={new Date(+now + 31536000000)}
                />
            </div>
        );
    }
}

/**
 * 控件：发布活动控制器
 * 发布活动
 */
@addon('ChangeActivityView', '发布活动', '发布活动')
@reactControl(Form.create<any>()(ChangeActivityView), true)
export class ChangeActivityViewControl extends BaseReactElementControl {

}